<template>
  <div>
    <div class="search_box">
      <el-input v-model="pag.name" placeholder="配件名"></el-input>
      <el-date-picker
        v-model="pag.entry_time"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      >
      </el-date-picker>
      <el-button type="primary" @click="getList">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>
    <div class="export_box">
      <el-button type="primary" @click="printListData">数据导出</el-button>
      <el-button type="primary" @click="addItem">入库</el-button>
    </div>
    <el-table :data="tableData" style="width: 100%" :height="h" border>
      <el-table-column prop="entry_time" label="入库时间" align="center">
      </el-table-column>
      <el-table-column
        prop="type1"
        label="配件总类别"
        align="center"
        width="100px"
      >
      </el-table-column>
      <el-table-column
        prop="type2"
        label="配件子类别"
        align="center"
        width="100px"
      >
      </el-table-column>
      <el-table-column prop="name" label="配件名称" width="120" align="center">
      </el-table-column>
      <el-table-column prop="type3" label="入库类型" align="center">
      </el-table-column>
      <el-table-column prop="num" label="库存数量" align="center">
      </el-table-column>
      <el-table-column prop="units" label="计量单位" align="center">
      </el-table-column>
      <el-table-column prop="unit_price" label="入库单价" align="center">
      </el-table-column>
      <el-table-column prop="total_price" label="总金额" align="center">
      </el-table-column>

      <el-table-column prop="distribution_name" label="配送单位" align="center">
      </el-table-column>
      <el-table-column prop="entry_name" label="入库人" align="center">
      </el-table-column>
      <el-table-column prop="remark" label="备注" align="center">
      </el-table-column>
      <el-table-column label="操作" align="center" width="120">
        <template slot-scope="scope">
          <el-button type="text" @click="issueData(scope.row)">出库</el-button>
          <el-button type="text" @click="editData(scope.row)">编辑</el-button>
          <el-button type="text" @click="delData(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page_table">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="1"
        :page-sizes="[10, 20, 30]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pag.total"
      >
      </el-pagination>
    </div>
    <!-- 录入 -->
    <!-- 录入 -->
    <el-dialog
      title="配件入库"
      :visible.sync="visible"
      width="720px"
      :before-close="handleClose"
    >
      <el-form
        :inline="true"
        :model="form"
        class="demo-form-inline"
        label-width="130px"
        ref="ruleForm"
        :rules="rules"
      >
        <el-form-item label="配件总类别" prop="type1">
          <el-input v-model="form.type1"></el-input>
        </el-form-item>
        <el-form-item label="配件子类别" prop="type2">
          <el-input v-model="form.type2"></el-input>
        </el-form-item>
        <el-form-item label="配件名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="入库类型" prop="type3">
          <el-input v-model="form.type3"></el-input>
        </el-form-item>
        <el-form-item label="计量单位" prop="units">
          <el-input v-model="form.units"></el-input>
        </el-form-item>
        <el-form-item label="入库数量" prop="num">
          <el-input
            v-model="form.num"
            @input="changprice"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="入库单价" prop="unit_price">
          <el-input
            v-model="form.unit_price"
            @input="changprice"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="总金额" prop="total_price">
          <el-input v-model="form.total_price" disabled></el-input>
        </el-form-item>
        <el-form-item label="入库时间" prop="entry_time">
          <el-date-picker
            v-model="form.entry_time"
            type="date"
            value-format="yyyy/MM/dd"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="入库人" prop="entry_name">
          <el-input v-model="form.entry_name"></el-input>
        </el-form-item>
        <el-form-item label="付款单位" prop="our_id">
          <el-select v-model="form.our_id" @change="changeOur" filterable>
            <el-option
              v-for="item in ourList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="配送单位" prop="distribution">
          <el-select v-model="form.distribution" @change="changeSu" filterable>
            <el-option
              v-for="item in suList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitAdd">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="配件出库"
      :visible.sync="issue_visible"
      width="720px"
      :before-close="handleClose"
    >
      <el-form
        :inline="true"
        :model="issueForm"
        class="demo-form-inline"
        label-width="130px"
        ref="rulesForm"
        :rules="rules1"
      >
        <el-form-item label="配件总类别" prop="type1">
          <el-input v-model="issueForm.type1" disabled></el-input>
        </el-form-item>
        <el-form-item label="配件子类别" prop="type2">
          <el-input v-model="issueForm.type2" disabled></el-input>
        </el-form-item>
        <el-form-item label="配件名称" prop="name">
          <el-input v-model="issueForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="出库类型" prop="type3">
          <el-input v-model="issueForm.type3" disabled></el-input>
        </el-form-item>
        <el-form-item label="计量单位" prop="units">
          <el-input v-model="issueForm.units" disabled></el-input>
        </el-form-item>
        <el-form-item label="剩余库存" prop="num1">
          <el-input v-model="issueForm.num1" disabled></el-input>
        </el-form-item>
        <el-form-item label="出库数量" prop="num">
          <el-input
            v-model="issueForm.num"
            @input="changprice1"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="出库单价" prop="unit_price">
          <el-input
            v-model="issueForm.unit_price"
            type="number"
            @input="changprice1"
          ></el-input>
        </el-form-item>
        <el-form-item label="总金额" prop="total_price">
          <el-input v-model="issueForm.total_price" disabled></el-input>
        </el-form-item>
        <br />
        <el-form-item label="出库人" prop="issue_person">
          <el-input v-model="issueForm.issue_person"></el-input>
        </el-form-item>
        <el-form-item label="出库时间" prop="issue_time">
          <el-date-picker
            v-model="issueForm.issue_time"
            type="date"
            value-format="yyyy/MM/dd"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="接受单位" prop="receiving">
          <el-input
            v-model="issueForm.receiving"
            type="textarea"
            :rows="2"
          ></el-input>
        </el-form-item>

        <el-form-item label="使用车辆" prop="use_plate">
          <el-input v-model="issueForm.use_plate"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="issueForm.remark"
            type="textarea"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitAdd1">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDataByKey, openDB, changeDB, deleteDB, editDB } from "@/db/indexdb";
import { searchTable } from "@/db/search";
import { printData } from "@/db/print";
export default {
  data() {
    return {
      visible: false,
      issue_visible: false,
      issueForm: {
        accessories_id: "",
        type1: "",
        type2: "",
        type3: "",
        name: "",
        units: "",
        num1: "",
        num: "",
        unit_price: "",
        total_price: "",
        issue_person: "",
        issue_time: "",
        receiving: "",
        use_plate: "",
        remark: "",
      },
      form: {
        type1: "",
        type2: "",
        type3: "",
        name: "",
        units: "",
        num: "",
        unit_price: "",
        total_price: "",
        entry_time: "",
        entry_name: "",
        distribution: "",
        remark: "",
        our_id: "",
      },
      rules: {
        type1: [{ required: true, message: "请输入总类别", trigger: "blur" }],
        type2: [{ required: true, message: "请输入子类别", trigger: "blur" }],
        name: [{ required: true, message: "请输入配件名称", trigger: "blur" }],
        num: [{ required: true, message: "请输入入库数量", trigger: "blur" }],
        unit_price: [
          { required: true, message: "请输入配件单价", trigger: "blur" },
        ],
        entry_time: [
          { required: true, message: "请选择入库时间", trigger: "blur" },
        ],
        our_id: [
          { required: true, message: "请选择付款单位", trigger: "blur" },
        ],
        distribution: [
          { required: true, message: "请输入配送单位", trigger: "blur" },
        ],
      },
      rules1: {
        num: [{ required: true, message: "请输入出库数量", trigger: "blur" }],
        unit_price: [
          { required: true, message: "请输入出库单价", trigger: "blur" },
        ],
        issue_time: [
          { required: true, message: "选择出库时间", trigger: "blur" },
        ],
      },

      tableData: [],
      pag: {
        name: "",
        entry_time: [],
        total: 0,
        page: 1,
        size: 10,
      },
      edit: false, // 0:新增 1:编辑 2:出库
      suList: [],
      ourList: [],
      h: "",
      totalList: [],
    };
  },
  created() {
    openDB("car", "list").then(() => {
      this.getList();
      this.getOther();
    });
    this.h = document.documentElement.offsetHeight - 270;
  },
  methods: {
    printListData() {
      let header = [
        { value: "entry_time", label: "入库时间", first: 1 },
        { value: "type1", label: "配件总类别" },
        { value: "type2", label: "配件子类别" },
        { value: "name", label: "配件名称" },
        { value: "type3", label: "入库类型" },
        { value: "num", label: "库存数量", type: "n", total: 1 },
        { value: "units", label: "计量单位" },
        { value: "unit_price", label: "入库单价", type: "n" },
        { value: "total_price", label: "总金额", type: "n", total: 1 },
        { value: "distribution_name", label: "配送单位" },
        { value: "entry_name", label: "入库人" },
        { value: "remark", label: "备注" },
      ];
      let msg = {
        msg1: "库存表",
      };
      printData(msg, this.totalList, header);
    },
    resetSearch() {
      this.pag = {
        name: "",
        entry_time: [],
        total: 0,
        page: 1,
        size: 10,
      };
      this.getList();
    },
    getList() {
      getDataByKey("list", "库存表").then((res) => {
        let { total, list, totalList } = searchTable(res?.data, this.pag, 1);
        this.totalList = totalList;
        this.pag.total = total;
        this.tableData = list;
      });
    },
    getOther() {
      getDataByKey("list", "供应商表").then((res) => {
        this.suList = res?.data;
      });
      getDataByKey("list", "公司信息表").then((res) => {
        this.ourList = res?.data;
      });
    },
    changeSu(val) {
      let result =
        this.suList.filter((item) => {
          return item.id == val;
        })[0].name || "";
      this.form.distribution_name = result;
    },
    changeOur(val) {
      let result =
        this.ourList.filter((item) => {
          return item.id == val;
        })[0].name || "";
      this.form.our_name = result;
    },
    submitAdd() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          let data = { ...this.form };
          data.start_time = data.entry_time;
          data.end_time = data.entry_time;
          if (this.edit) {
            editDB("list", "库存表", data).then((res) => {
              this.getList();
              this.addIncome(data);
              this.$message.success("修改成功");
            });
          } else {
            data.id = new Date().getTime();
            changeDB("list", "库存表", data).then(() => {
              this.addIncome(data);
              this.getList();
              this.$message.success("入库成功");
            });
          }
          this.handleClose();
        } else {
          return false;
        }
      });
    },
    async addIncome(data) {
      getDataByKey("list", "收付款表").then(async (res) => {
        let incomeArr = res?.data;
        let data1 = {
          item_type: 2,
          type: 5,
          cars_id: data.id,
          project_id: data.id,
          project_name: "配件入库",
          receivable: data.distribution_name || "",
          receivable_id: data.distribution || "",
          payable: data.our_name || "",
          payable_id: data.our_id || "",
          total_price: data.total_price,
          abstract: data.name,
        };
        let flag = incomeArr.filter((item) => {
          return item.cars_id == data1.cars_id;
        });
        if (flag.length > 0) {
          data1.id = flag[0].id;
          await editDB("list", "收付款表", data1).then(() => {});
        } else {
          data1.id = Number(new Date().getTime());
          await changeDB("list", "收付款表", data1).then(() => {});
        }
      });
    },
    handleClose() {
      this.edit = false;
      this.visible = false;
      this.issue_visible = false;
      this.form = {};
      this.issueForm = {};
    },
    changprice() {
      let item = this.form;
      if (item.num > 0 && item.unit_price > 0) {
        this.form.total_price = item.num * item.unit_price;
        this.form.total_price = this.form.total_price.toFixed(4);
      } else {
        this.form.total_price = "";
      }
    },
    changprice1() {
      let item = this.issueForm;

      if (Number(item.num) > Number(item.num1)) {
        this.$message.warning("出库数量大于库存数量!");
        this.issueForm.num = "";
      } else {
        if (item.num > 0 && item.unit_price > 0) {
          this.issueForm.total_price = item.num * item.unit_price;
          this.issueForm.total_price = this.issueForm.total_price.toFixed(4);
        } else {
          this.issueForm.total_price = "";
        }
      }
    },
    addItem() {
      this.visible = true;
    },
    delData(id) {
      deleteDB("list", "库存表", id)
        .then(() => {
          this.getList();
          this.visible = false;
        })
        .catch((res) => {
          console.log(res);
        });
    },
    editData(row) {
      this.edit = true;
      this.visible = true;
      this.form = { ...row };
    },
    issueData(row) {
      this.issue_visible = true;
      this.form = { ...row };
      let data = { ...row };
      this.issueForm = {
        accessories_id: data.id,
        type1: data.type1,
        type2: data.type2,
        type3: data.type3,
        name: data.name,
        units: data.units,
        num1: data.num,
        num: "",
        unit_price: "",
        total_price: "",
        issue_person: "",
        issue_time: "",
        receiving: "",
        use_plate: "",
        remark: "",
      };
    },
    submitAdd1() {
      this.$refs["rulesForm"].validate((valid) => {
        if (valid) {
          let data = { ...this.issueForm };
          data.id = new Date().getTime();
          data.start_time = data.issue_time;
          data.end_time = data.issue_time;
          changeDB("list", "出入库明细表", data).then(() => {
            let data1 = { ...this.form };
            data1.num = Number(data1.num) - Number(data.num);
            editDB("list", "库存表", data1).then((res) => {
              this.getList();
              this.handleClose();
              this.$message.success("出库成功");
            });
          });
        } else {
          return false;
        }
      });
    },
    handleSizeChange(val) {
      this.pag.size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pag1.page = val;
      this.getList();
    },
  },
};
</script>

<style lang="scss" scoped>
.search_box {
  display: flex;
  flex-wrap: wrap;
  border-bottom: 1px solid #ccc;
  .el-input,
  .el-select {
    width: 200px;
    margin-right: 20px;
    margin-bottom: 20px;
  }
  .el-date-editor {
    margin-right: 20px;
    margin-bottom: 20px;
  }
  .el-button {
    margin-bottom: 20px;
  }
}
.export_box {
  display: flex;
  justify-content: flex-end;
  margin: 10px 0;
}
.page_table {
  margin-top: 20px;
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
.el-form {
  .el-select,
  .el-input,
  .el-date-editor {
    width: 200px;
  }
  .el-textarea {
    width: 540px;
  }
}
</style>
